import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { setCollapsed } from "../../store/reducers/tab";
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { Button, Layout, Avatar, Dropdown, MenuProps } from "antd";
import "./index.css";

import userAvatar from "../../assets/images/user.jpg";

const { Header } = Layout;

// 定义组件的属性接口
interface CommonHeaderProps {
  collapsed: boolean;
  colorBgContainer: string;
  borderRadiusLG?: number;
}

const CommonHeader: React.FC<CommonHeaderProps> = ({
  collapsed,
  colorBgContainer,
}) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [userName, setUserName] = useState<string>("");

  // 登出处理函数
  const logOut = () => {
    localStorage.removeItem("token");
    navigate("/login");
  };

  // 模拟获取用户信息的API调用
  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const response = await fetch("/api/user/info");
        const data = await response.json();
        setUserName(data.name);
      } catch (error) {
        console.error("Failed to fetch user info:", error);
      }
    };

    fetchUserInfo();
  }, []);

  // 下拉菜单项配置
  const items: MenuProps["items"] = [
    {
      key: "1",
      label: (
        <a target="_blank" rel="noopener noreferrer" href="/">
          个人中心
        </a>
      ),
    },
    {
      key: "2",
      label: (
        <a onClick={logOut} target="_blank" rel="noopener noreferrer" href="/">
          退出
        </a>
      ),
    },
  ];

  // 处理折叠/展开操作
  const handleCollapsed = () => {
    dispatch(setCollapsed(!collapsed));
  };

  return (
    <Header
      className="header-container"
      style={{
        padding: 0,
        background: colorBgContainer,
        paddingLeft: 24,
      }}
    >
      <Button
        type="text"
        icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        onClick={handleCollapsed}
        style={{
          fontSize: "20px",
          width: 64,
          height: 64,
        }}
      />

      <Dropdown placement="bottom" menu={{ items }}>
        <Avatar className="avatar" size="large" src={userAvatar}>
          {userName}
        </Avatar>
      </Dropdown>
    </Header>
  );
};

export default CommonHeader;
